package com.edu.chat.web.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.buservice.util.model.TenantUtil;
import com.edu.chat.web.common.enums.ResultCodeEnum;
import com.edu.chat.web.common.model.BizException;
import com.edu.chat.web.common.model.R;
import com.edu.chat.web.dto.DocumentDTO;
import com.edu.chat.web.model.CsDocuments;
import com.edu.chat.web.service.CsDocumentsService;
import com.edu.chat.web.mapper.CsDocumentsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 86177
 * @description 针对表【cs_documents(文档信息表)】的数据库操作Service实现
 * @createDate 2025-04-06 10:47:21
 */
@Service
@Slf4j
public class CsDocumentsServiceImpl extends ServiceImpl<CsDocumentsMapper, CsDocuments>
		implements CsDocumentsService{

	@Override
	public R<Boolean> createDocuments(DocumentDTO document) {

		if(document == null) {
			throw new BizException(ResultCodeEnum.PARAM_INVALID, "文档内容不能为空");
		}

		if(document.getContent() == null) {
			throw new BizException(ResultCodeEnum.PARAM_INVALID, "文档内容不能为空");
		}


		CsDocuments csDocuments = new CsDocuments();
		csDocuments.setContent(document.getContent());
		csDocuments.setFileId(document.getFileId());
		csDocuments.setMetadata(JSONUtil.toJsonStr(document.getMetadata()));
		csDocuments.setTenantId(TenantUtil.getTenantId());

		boolean save = save(csDocuments);

		if(!save) {
			throw new BizException(ResultCodeEnum.FAIL, "保存失败");
		}
		return R.success(true);
	}

	@Override
	public R<Boolean> createDocumentsBatch(List<DocumentDTO> documents) {

		// 参数校验
		if (CollectionUtil.isEmpty(documents)) {
			throw new BizException(ResultCodeEnum.PARAM_INVALID, "文档内容不能为空");
		}

		try {
			// 转换 DTO 到实体对象
			List<CsDocuments> csDocuments = documents.stream()
					.map(document -> {
						if (document.getContent() == null || document.getFileId() == null) {
							throw new BizException(ResultCodeEnum.PARAM_INVALID, "文档内容或文件ID不能为空");
						}
						CsDocuments doc = new CsDocuments();
						doc.setContent(document.getContent());
						doc.setFileId(document.getFileId());
						doc.setId(document.getId());
						// 校验并转换 metadata
						doc.setMetadata(JSONUtil.toJsonStr(document.getMetadata()));
						return doc;
					})
					.collect(Collectors.toList()); // 兼容 Java 16 之前的版本

			// 批量保存
			boolean flag = saveBatch(csDocuments);
			if (!flag) {
				log.error("批量保存文档失败，文档列表：{}", documents); // 记录失败日志
				throw new BizException(ResultCodeEnum.FAIL, "保存失败");
			}

			return R.success(true);

		} catch (BizException e) {
			log.error("创建文档批次失败：{}", e.getMessage(), e); // 记录异常日志
			throw e; // 重新抛出异常
		}
	}

	@Override
	public R<List<String>> deleteDocuments(String fileId) {

		if(fileId == null) {
			throw new BizException(ResultCodeEnum.PARAM_INVALID, "文档内容不能为空");
		}

		//查询文档

		LambdaQueryWrapper<CsDocuments> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(CsDocuments::getFileId, fileId);
		queryWrapper.eq(CsDocuments::getTenantId, TenantUtil.getTenantId());
		queryWrapper.eq(CsDocuments::getDeleted, 0);

		List<CsDocuments> list = list(queryWrapper);
		if(CollectionUtil.isEmpty(list)) {
			log.error("文档不存在,文件ID:{}", fileId);
			return R.success();
		}

		boolean remove = remove(queryWrapper);

		if(!remove) {
			throw new BizException(ResultCodeEnum.FAIL, "删除失败");
		}

		Set<String> docIds =  list.stream().map(CsDocuments::getId).map(String::valueOf).collect(Collectors.toSet());
		return R.success(new ArrayList<>(docIds));

	}

}




